﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
using ArtOfTest.WebAii.Core;
using ArtOfTest.WebAii.TestTemplates;
using SM2ObjectRunner;
using System.Diagnostics;
using Utilities;

namespace SM2TestRunner
{
    public class TestRunner : BaseTest
    {
        public void run(TestSuite TestSuiteItem)
        {
            if (TestSuiteItem != null)
            {
                //Get Server & Browser out from the last record
                Utilities.GlobalRunning.strSERVER = TestSuiteItem.getTestSuiteSERVER();

                //Load server details
                try
                {
                    Utilities.GlobalInit.loadValueForGlobalServerDetail();
                }
                catch (Exception ex)
                {
                    Utilities.GlobalObject.LOGGER.log("Failed to load Server Details [" + Utilities.GlobalRunning.strSERVER + "]");
                    Utilities.GlobalObject.LOGGER.log(ex.ToString());
                }

                //Run
                TestSuiteRun(TestSuiteItem);

                //Cln
                cln();
            }            
        }

        public void TestSuiteRun(TestSuite tsItem)
        {
            //For optimize lauching browser & login action
            string strCurrentUser = "";

            //Get first TEST_CASE
            Utilities.GlobalTestStep.intTotalTestCase = tsItem.countTestCase();
            TestCase tcItem = tsItem.getTestCase();
            int intTCOrder = 0;
            while (tcItem != null)

            #region start while
            {
                //Count order of test case (also the number of test case have been executed)
                Utilities.GlobalTestStep.intTestCaseOrder = ++intTCOrder;

                //Build Test Header for report
                Utilities.GlobalObject.REPORT.createNewTestCaseHeader();

                //Get first TEST_STEP
                TestStep teststepItem = tcItem.getTestStep();
                int intTSOrder = 0;

                while (teststepItem != null)
                {
                    Utilities.GlobalTestStep.intTestStepOrder = ++intTSOrder;
                    Utilities.GlobalTestStep.strOwner = teststepItem.getOwner();
                    Utilities.GlobalTestStep.strObject = teststepItem.getObjectName();
                    Utilities.GlobalTestStep.strAction = teststepItem.getAction();
                    TestDispatcher.TEST_PARAMETER = teststepItem.getParameters();
                    Utilities.GlobalTestStep.strValidation = teststepItem.getValidation();

                    //Core run
                    try
                    {
                        //Launch
                        if (strCurrentUser.Equals("") || !strCurrentUser.Equals(Utilities.GlobalTestStep.strOwner))
                        {
                            //If currentUser is blank : means there is no login yet
                            // or if new owner differs to currentUser
                            init();
                        }

                        //Login
                        if (!Utilities.GlobalTestStep.strAction.Equals("loginValidate") && !Utilities.GlobalTestStep.strAction.Equals("LaunchSandbox"))
                        {
                            //Login with correct user if this is not loginValidate action
                            //Need to check if not login yet --> login
                            if (!Utilities.GlobalObject.MANAGER.ActiveBrowser.ContainsText("User:") && !Utilities.GlobalObject.MANAGER.ActiveBrowser.ContainsText("Profile:"))
                            {
                                Assembly asblNameSpace = Assembly.LoadFrom("SM2WelcomePage.dll");
                                Type typeOfClass = asblNameSpace.GetType("SM2WelcomePage.SM2");
                                IObject iobjectLogin = (IObject)Activator.CreateInstance(typeOfClass);
                                iobjectLogin.run("loginSuccess");
                            }
                        }
                        else
                        {
                            //Log-off for validation login if not log-off yet
                            if (Utilities.GlobalObject.MANAGER.ActiveBrowser.ContainsText("Profile"))
                            {
                                //LOG OFF
                                Assembly asblNameSpace = Assembly.LoadFrom("SM2WelcomePage.dll");
                                Type typeOfClass = asblNameSpace.GetType("SM2WelcomePage.SM2");
                                IObject iobjectLogin = (IObject)Activator.CreateInstance(typeOfClass);
                                iobjectLogin.run("logoff");
                            }
                        }

                        //Set strCurrentUser
                        strCurrentUser = Utilities.GlobalTestStep.strOwner;

                        //Call object to run
                        ORunner OBJECT_ENGINE = new ORunner();
                        OBJECT_ENGINE.run();

                        //Add passed row into report
                        Utilities.GlobalObject.REPORT.createNewTestStepItemPass(TestDispatcher.TEST_PARAMETER.buildTestData());
                    }
                    catch (Exception EX)
                    {

                        //Reset
                        Utilities.GlobalTestStep.strValidation = "";
                        TestDispatcher.TEST_PARAMETER = new TestParameters();

                        //Log & report
                        string strEX = EX.ToString();
                        Utilities.GlobalObject.LOGGER.log(strEX);
                        if (strEX.Contains("validateTextPresentInPage"))
                            Utilities.GlobalObject.REPORT.createNewTestStepItemFailByValidtion(TestDispatcher.TEST_PARAMETER.buildTestData());
                        else
                            Utilities.GlobalObject.REPORT.createNewTestStepItemFail(TestDispatcher.TEST_PARAMETER.buildTestData());
                    }

                    //Get next TEST_STEP
                    teststepItem = tcItem.getTestStep();

                    //Reset
                    Utilities.GlobalTestStep.strValidation = "";
                    TestDispatcher.TEST_PARAMETER = new TestParameters();
                }

                //Get next TEST_CASE
                tcItem = tsItem.getTestCase();
            }
            #endregion

            //Close browser
            Utilities.GlobalObject.MANAGER.ActiveBrowser.Close();
            Utilities.GlobalObject.MANAGER.Dispose();
        }

        public void init()
        {
            switch (Utilities.GlobalRunning.strBROWSER.ToUpper())
            {
                case "IE":
                    Utilities.GlobalObject.SETTINGS = new Settings(BrowserType.InternetExplorer, Utilities.GlobalFolder.REPOSITORY_WEBAii_LOG, Utilities.GlobalRunning.SERVER_URL);
                    break;
                case "FF":
                    Utilities.GlobalObject.SETTINGS = new Settings(BrowserType.FireFox, Utilities.GlobalFolder.REPOSITORY_WEBAii_LOG, Utilities.GlobalRunning.SERVER_URL);
                    break;
                case "GG":
                    Utilities.GlobalObject.SETTINGS = new Settings(BrowserType.Chrome, Utilities.GlobalFolder.REPOSITORY_WEBAii_LOG, Utilities.GlobalRunning.SERVER_URL);
                    break;
                case "SF":
                    Utilities.GlobalObject.SETTINGS = new Settings(BrowserType.Safari, Utilities.GlobalFolder.REPOSITORY_WEBAii_LOG, Utilities.GlobalRunning.SERVER_URL);
                    break;
                default:
                    break;
            }

            Utilities.GlobalObject.SETTINGS.Web.EnableSilverlight = true;
            Utilities.GlobalObject.SETTINGS.Web.SilverlightConnectTimeout = 60000;
            Utilities.GlobalObject.SETTINGS.ExecuteCommandTimeout = 60000;

            Utilities.GlobalObject.MANAGER = new Manager(Utilities.GlobalObject.SETTINGS);
            Utilities.GlobalObject.MANAGER.Start();
            Utilities.GlobalObject.MANAGER.LaunchNewBrowser();
            Utilities.GlobalObject.MANAGER.ActiveBrowser.Window.Maximize();
            Utilities.GlobalObject.MANAGER.ActiveBrowser.NavigateTo(Utilities.GlobalRunning.SERVER_URL);
            Utilities.GlobalObject.MANAGER.ActiveBrowser.WaitUntilReady();
            System.Threading.Thread.Sleep(5000);
        }

        public void cln()
        {
            this.CleanUp();
        }    
    }
}
